package com.longcai.cm.api.listener;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.longcai.cm.common.utils.StringUtil;
import com.longcai.cm.domain.*;
import com.longcai.cm.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author libingxing
 */
@Component
public class CommonSchedule {

    @Resource
    private JaMemberCouponsService memberCouponsService;

    @Resource
    private JaCouponService couponService;

    @Resource
    private JaMemberVipService memberVipService;

    @Resource
    private JaOrderService orderService;

    @Resource
    private JaOrderRefundApplyService orderRefundApplyService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Async
    @Scheduled(cron = "0 0 3 * * ?")
    public void sendVipCoupons(){
//        每月1号会员定期发放优惠券
        final List<JaMemberVip> vipList = memberVipService.lambdaQuery()
                .select(JaMemberVip::getMemberId)
                .gt(JaMemberVip::getExpireTime, DateUtil.now())
                .eq(JaMemberVip::getPushTime, DateUtil.date().dayOfMonth())
                .eq(JaMemberVip::getLevel, 2)
                .list();
        if (vipList.size() > 0) {
            final List<JaCoupon> couponList = couponService.lambdaQuery().eq(JaCoupon::getSource, 2).list();
            final List<Integer> memberIdList = vipList.stream().map(JaMemberVip::getMemberId).collect(Collectors.toList());
            final List<String> couponIds = couponList.stream().map(JaCoupon::getId).collect(Collectors.toList());
//            批量过期 先前优惠券
            for (Integer id : memberIdList) {
//                查看本月是否发放过
                memberCouponsService.lambdaUpdate().eq(JaMemberCoupons::getMemberId, id)
                        .in(JaMemberCoupons::getCouponsId, couponIds).set(JaMemberCoupons::getStatus, 2).update();
                final Long hasList = memberCouponsService.lambdaQuery()
                        .eq(JaMemberCoupons::getCouponsId, couponIds)
                        .eq(JaMemberCoupons::getMemberId, id)
                        .like(JaMemberCoupons::getCreateTime, DateUtil.today().substring(0, 7))
                        .count();
                if (hasList == 0) {
                    for (JaCoupon coupon : couponList) {
                        memberCouponsService.addCoupons(coupon.getId(), coupon.getNum(), id);
                    }
                }
            }
        }
    }

    @Async
    @Scheduled(cron = "0 * * * * ?")
    public void sendCouponsExpire(){
//        会员定期过期优惠券
        logger.info("优惠券定时过期");
        memberCouponsService.lambdaUpdate()
                .le(JaMemberCoupons::getExpireTime, DateUtil.now())
                .eq(JaMemberCoupons::getStatus, 0)
                .set(JaMemberCoupons::getStatus, 2)
                .update();
    }

    @Async
    @Scheduled(cron = "0 * * * * *")
    public void refundExpireGoodInfo(){
//        查找已过期订单 退款处理
        LambdaQueryWrapper<JaOrder> query = new LambdaQueryWrapper<>();
        query.eq(JaOrder::getOrderStatus, 1);
        query.le(JaOrder::getExpireTime, DateUtil.now());
        final List<JaOrder> list = orderService.list(query);
        if (list.size() > 0) {
            for (JaOrder order : list) {
                try {
                    orderService.refundOrder(order.getPayAmount(), order.getPayAmount(), order.getOrderNum(), order.getPayType());
                } catch (Exception e) {
                    logger.info("订单：" + order.getId() + "商品超出有效期 退款失败-" + e.getMessage());
                }
                JaOrderRefundApply refund = new JaOrderRefundApply();
                refund.setId(StringUtil.getUuid());
                refund.setOrderId(order.getId());
                refund.setRefundReason("商品超出有效期，已退款");
                refund.setMemberId(order.getMemberId());
                refund.setStatus(1);
                refund.setRefundNum(order.getOrderNum().replace("C", "R"));
                refund.setRefundAmount(order.getPayAmount());
                orderRefundApplyService.save(refund);
            }
            orderService.lambdaUpdate().in(JaOrder::getId, list.stream().map(JaOrder::getId).collect(Collectors.toList()))
                    .set(JaOrder::getOrderStatus, 5)
                    .update();
        }
    }
}
